//
//  HTPremiumCard.swift
//  MagaCore
// 6
//  Created by 罗林轩 on 2024/9/2.
//  Copyright © 2024 HT. All rights reserved.
//

import SwiftUI

struct Card: View {
    @ObservedObject var model: HTPremiumCardModel
    var body: some View {
        ZStack {
            Image(model.isSelected ? model.sel_img : model.nor_img)
                .frame(width: 100, height: 122)
            VStack {
                Text("测试")
                    .ht_commonTextStyle(color: .white, fontSize: 14, weight: .regular)
                Text("测试")
                    .ht_commonTextStyle(color: .white, fontSize: 24, weight: .bold)
                Text("测试")
                    .ht_commonTextStyle(color: .white, fontSize: 12, weight: .bold)
                    .underline()
            }
        }
        .onTapGesture {
            model.isSelected = !model.isSelected
            NotificationCenter.default.post(name: HTConfig.STATIC_notification_changeCard, object: nil, userInfo: ["model": model])
        }
    }
}

class HTPremiumCardModel: ObservableObject {
    @Published var isSelected: Bool = false
    var nor_img: String
    var sel_img: String

    init(isSelected: Bool, nor_img: String, sel_img: String) {
        self.isSelected = isSelected
        self.nor_img = nor_img
        self.sel_img = sel_img
    }
}

class HTPremiumCardViewModel: ObservableObject {
    @Published var models: [HTPremiumCardModel] = [
        HTPremiumCardModel(isSelected: false, nor_img: "Frame 1095", sel_img: "Frame 2277"),
        HTPremiumCardModel(isSelected: true, nor_img: "Frame 2273", sel_img: "Frame 2279"),
        HTPremiumCardModel(isSelected: false, nor_img: "Frame 2274", sel_img: "Frame 2280"),
        HTPremiumCardModel(isSelected: false, nor_img: "Frame 2275", sel_img: "Frame 2278"),
        HTPremiumCardModel(isSelected: false, nor_img: "Frame 2276", sel_img: "Frame 2281")]
}

struct HTPremiumCard: View {
    @ObservedObject var viewModel: HTPremiumCardViewModel = HTPremiumCardViewModel()
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(viewModel.models, id: \.self.nor_img) { model in
                    Card(model: model)
                }
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: HTConfig.STATIC_notification_changeCard), perform: { notifier in
            if let model = (notifier.userInfo! as! [String: HTPremiumCardModel])["model"] {
                viewModel.models.forEach { m in
                    if m !== model {
                        m.isSelected = false
                    }
                }
            }
        })
    }
}

#Preview {
    HTPremiumCard()
}
